import { message, Upload } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import React from 'react'
import { useState,useRef } from 'react'
import { useEffect,useImperativeHandle,forwardRef } from 'react'




const UploadImg = (props,parentRef) => {
    const inputRef = useRef()
    useImperativeHandle(parentRef, () => {
        // return返回的值就可以被父组件获取到
        return {
            focus() {
            return myFileList
          }
        }
      })
    // 图片列表
   const [myFileList,setMyFileList] = useState([])
   const fileRef = useRef(myFileList)
//    上传按钮
   const uploadButton = (
    <div>
      <PlusOutlined />
    </div>
  )
//   图片上传事件
    const uploadHandler = ({file,fileList})=>{
        if(!file.status) return
        setMyFileList(fileList)
        fileRef.current = fileList
    }

    useEffect(()=>{
        setMyFileList(fileRef.current.slice(0, props.imgLength))
    },[props.imgLength])

    useEffect(()=>{
      setMyFileList(props.articleImgList.map(item=>({url:item})))
      fileRef.current = props.articleImgList.map(item=>({url:item})) 
    },[props.articleImgList])

    // 上传图片前的校验
    const beforeUploadHandler =(file)=>{
        const whiteList = ['image/jpeg','image/png','image/gif','image/jpg']
        const isJpgOrPng =whiteList.includes(file.type)
        if (!isJpgOrPng)  message.error('图片格式必须为jpeg/png/gif/jpg')
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) message.error('图片大小不得超过 2MB!')
        return isJpgOrPng && isLt2M;
    }
    
     
  return   <>
        
        <Upload
        ref={inputRef}
        name="image"
        listType="picture-card"
        className="avatar-uploader"
        fileList={myFileList}
        maxCount={props.imgLength}
        onChange={uploadHandler}
        beforeUpload={beforeUploadHandler}
        action="http://geek.itheima.net/v1_0/upload"
      >
        {myFileList.length === props.imgLength ? null: uploadButton}
      </Upload>
      </>
}
let ForwardChidl = forwardRef(UploadImg);

export default ForwardChidl